package com.corgi.formatter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
 * @title: JsonFormatter
 * @description: Jackson JSON {@link Formatter} 实现
 * @author: dengmiao
 * @create: 2019-10-10 14:12
 **/
@Slf4j
public class JsonFormatter<T> implements Formatter<T, String> {

	private final ObjectMapper objectMapper;

	public JsonFormatter() {
		this(new ObjectMapper());
	}

	public JsonFormatter(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	@Override
	public String format(Object o) {
		try {
			return objectMapper.writeValueAsString(o);
		} catch (JsonProcessingException e) {
			// 解析失败返回非法参数异常
			throw new IllegalArgumentException(e);
		}
	}

	@Override
	public T parse(String json, Class<T> clazz) {
		if (StringUtils.isEmpty(json) || clazz == null) {
			return null;
		}

		try {
			return clazz.equals(String.class) ? (T)json : objectMapper.readValue(json, clazz);
		} catch (Exception e) {
			// 解析失败返回非法参数异常
			throw new IllegalArgumentException(e);
		}
	}

}
